package com.yc.library.servlet;

import com.yc.library.bean.Book;
import com.yc.library.dao.BookDao;
import com.yc.library.mapper.BookMapper;
import com.yc.library.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/SaveBookServlet.do/*")
public class SaveBookServelt extends BaseServlet{
    private BookDao bdao = new BookDao();

    protected void SaveBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("bookname");
        String press = request.getParameter("bookpress");
        String date = request.getParameter("pressdate");
        String author = request.getParameter("bookauthor");
        String count = request.getParameter("bookcount");
        String image = request.getParameter("bookimage");
        System.out.println(id);
        System.out.println(name);
        System.out.println(press);
        System.out.println(date);
        System.out.println(author);
        System.out.println(count);
        System.out.println(image);
//        Map<String,Object> list = bdao.getBook(id);
//        if( list == null || list.isEmpty() ) { // 查无数据
//            this.send(response, 500, null);
//            return;
//        }
//        this.send(response, 200, list);
//        Date d = Date.valueOf(date);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        SqlSession session = MyBatisHelper.getsSession();

        BookMapper mapper = session.getMapper(BookMapper.class);
//        try {
////            bdao.save(id, name, press, date, author, count, image);
//            mapper.save(id, name, press, Date.valueOf(date), author, count, image);
//            response.getWriter().print("保存成功");
//        } catch (Exception e) {
//            response.getWriter().print("保存失败");
//        }

        try{
            mapper.save(id, name, press, date, author, count, image);
            response.getWriter().print("保存成功");
            // 如果成功则提交
            session.commit();
        } catch (Exception e){
            e.printStackTrace();
            response.getWriter().print("保存失败");
            // 如果异常则回滚
            session.rollback();
        } finally {
            // 不管正常还是异常都要关闭连接
            // 但是会话的关闭 != 连接的关闭
            // 池化的数据源关闭 == 归还链接
            session.close();
        }

    }
}
